#import "GuitarNotes.h"

@interface GuitarNotes ()
@property NSDictionary* guitarNotes;
@property NSMutableArray* songNotes;

@end

@implementation GuitarNotes

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.songNotes=[[NSMutableArray alloc]init];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Keys" ofType:@"plist"];
        self.guitarNotes = [NSDictionary dictionaryWithContentsOfFile:path];
        
    }
    return self;
}
-(NSInteger)midiNoteWithName:(NSString*)name{
    
    return  [[self.guitarNotes objectForKey:name]integerValue];
    
}


-(void)songNotesFromCoreDataForSong:(Song*) song{
    for(NSInteger index=0;index<6;index++){
        
   
        
        [self.songNotes addObject:[self stringNotesToArray:[[[song notes]objectAtIndex:index] notesString]]];
    }
}
-(NSInteger)numberOfCharacters{
    return [[self.songNotes objectAtIndex:0] count];
}

-(void)readFileWithName:(NSString*)fileName  {
    NSArray* allNotes=[[NSMutableArray alloc]init];
    NSString* filePath = fileName;
    NSString* fileRoot = [[NSBundle mainBundle]
                          pathForResource:filePath ofType:@"txt"];
 
    
    NSString* fileContents =
    [NSString stringWithContentsOfFile:fileRoot
                              encoding:NSUTF8StringEncoding error:nil];
    
    // first, separate by new line
    allNotes = [fileContents componentsSeparatedByCharactersInSet:
     [NSCharacterSet newlineCharacterSet]];
    for(NSInteger index = 0;index<6;index++){
        [self.songNotes addObject:[self stringNotesToArray:[allNotes objectAtIndex:index]]];
    }
  
    
   
}
-(NSString*)characterAtIndex:(NSInteger)index forLine:(NSInteger)line{
    
   
    
    return  [[self.songNotes objectAtIndex:line] objectAtIndex:index];
    
}
-(NSInteger)currentNoteWithCharacter:(NSString*)character forLine:(NSInteger) line{
    
    return [self midiNoteWithName:[NSString stringWithFormat:@"%@%@",[self characterAtIndex:0 forLine:line],character]];

    
}
-(NSMutableArray*)stringNotesToArray:(NSString*)string{
    NSMutableArray* singleLineNotes=[[NSMutableArray alloc]init];
    for(NSInteger index=0;index<string.length-1;index++){
        NSString* substring =[ string substringWithRange:NSMakeRange(index, 1)];
    
        if(![substring integerValue] != 0 || [substring isEqualToString:@"0"]){
            [singleLineNotes addObject:substring];
        }
        else{
            NSString* checkSubstring=[string substringWithRange:NSMakeRange(index+1, 1)];
            if([checkSubstring integerValue] != 0 || [checkSubstring isEqualToString:@"0"]){
                [singleLineNotes addObject:[string substringWithRange:NSMakeRange(index, 2)]];
                index++;
                
            }
            else{
                [singleLineNotes addObject:substring];
            }
        }
    }
    
    return singleLineNotes;
}



@end
